package com.hyk.commonLib.common.entity;

import com.hyk.commonLib.common.exception.CustomException;
import com.hyk.commonLib.common.exception.TokenExpiredException;

import java.io.Serializable;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.functions.Function;
import kotlin.collections.ArraysKt;

/**
 * Created by 贺玉琨 on 2019/5/26.
 */
public interface INetObj<T> extends Serializable {

    T getData();

    void setData(T data);

    String getStatusCode();

    void setStatusCode(String statusCode);

    void setStatusCodeAsError();

    void setStatusCodeAsSuccess();

    String getMessage();

    void setMessage(String message);

    boolean isSuccess();

    boolean isTokenExpired();

    default boolean isFail() {
        return !isSuccess();
    }

    static <U extends INetObj<?>> Function<U, ObservableSource<U>> getCheckFunction() {
        return t -> {
            if (!t.isSuccess()) {
                if (t.isTokenExpired()) {
                    return Observable.error(new TokenExpiredException());
                }
                return Observable.error(new CustomException(t.getMessage()));
            }
            return Observable.just(t);
        };
    }

    static boolean isSuccess(INetObj<?> netObj) {
        return netObj != null && netObj.isSuccess();
    }

    static boolean allSuccess(INetObj<?>... netObjList) {
        if (netObjList == null || netObjList.length == 0) return true;
        return ArraysKt.all(netObjList, iNetObj -> isSuccess(iNetObj));
    }
}
